package app.service.goods;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import app.model.goods.GoodsBase;
import app.model.goods.GoodsStock;
import app.model.goods.GoodsUserRel;
import app.util.ClassUtil;
import app.util.LoginUserUtil;
import app.util.StringUtil;
import base.PageInfo;
import base.dao.HibernateDao;
import base.service.BaseService;

@Service
public class GoodsBaseService extends BaseService {

	@Autowired
	private HibernateDao<GoodsBase> hibernateDao;
	
	@Override
	public HibernateDao<GoodsBase> getDao() {
		return this.hibernateDao;
	}
	
	/**
	 * 查询商品
	 * @param pageInfo
	 * @param goodsName 
	 * @return
	 */
	public PageInfo queryGoodsBasePage(PageInfo pageInfo, String goodsName) {
		String sql = "select * FROM goods_base_use_view a";
		if(StringUtil.isNotEmpty(goodsName)){
			sql += " and a.goods_name like '%"+goodsName+"%'";
		}
		PageInfo page = getDao().queryPageListBySql(pageInfo, sql);
		return page;
	}

	public void saveEntity(GoodsBase goodsBase,GoodsStock goodsStock) {
		getDao().save(goodsBase);
		String goodsId = goodsBase.getId();
		
		//保存库存
		goodsStock.setGoodsId(goodsId);
		getDao().save(goodsStock);
		//保存商品用户关系
		GoodsUserRel goodsUserRel = new GoodsUserRel();
		goodsUserRel.setGoodsId(goodsId);
		goodsUserRel.setGoodsName(goodsBase.getGoodsName());
		goodsUserRel.setUserId(LoginUserUtil.getLoginUser().getId());
		goodsUserRel.setUserName(LoginUserUtil.getLoginUser().getUserName());
		getDao().save(goodsUserRel);
	}

	public void updateEntity(GoodsBase goodsBase,GoodsStock goodsStock) {
		getDao().mergeAndUpdate(goodsBase);
		
		//更新库存
		String hql = "select o from GoodsStock a where a.goodsId ='"+goodsBase.getId()+"'";
		GoodsStock gs = (GoodsStock)getDao().queryObjectByHQL(hql);
		gs.setGoodsNum(goodsStock.getGoodsNum());
		getDao().mergeAndUpdate(gs);
		
	}

	public Map<String, Object> queryEntityById(String id) {
		String sql = "select * from goods_base_use_view a where a.id = '"+id+"'";
		Map<String, Object> map = getDao().queryMapBySql(sql);
		Map<String, Object> humpNamed = ClassUtil.toHumpNamed(map);
		return humpNamed;
	}

	public void delEntity(String ids) {
		if(!StringUtils.isEmpty(ids)){
			String[] idsArray = ids.split(",");
			for (int i = 0; i < idsArray.length; i++) {
				GoodsBase gb = new GoodsBase();
				gb.setId(idsArray[i]);
				getDao().del(gb);
			}
		}
	}

	/**
	 * 超市主页查询
	 * @param pageInfo
	 * @param goodsName
	 * @return
	 */
	public PageInfo queryGoodsBaseIndex(PageInfo pageInfo, String goodsName) {
		String sql = "select * FROM goods_base_use_view a";
		if(StringUtil.isNotEmpty(goodsName)){
			sql += " and a.goods_name like '%"+goodsName+"%'";
		}
		
		PageInfo page = getDao().queryPageListBySql(pageInfo, sql);
		return page;
	}
}
